Skip to content

fix(zod): generate string type for zod enums#1486

Closed
Sigmabrogz wants to merge 1 commit intomiddleapi:mainfrom
Sigmabrogz:fix/zod-enum-string-type
Closed

fix(zod): generate string type for zod enums#1486
Sigmabrogz wants to merge 1 commit intomiddleapi:mainfrom
Sigmabrogz:fix/zod-enum-string-type

Conversation

@Sigmabrogz
Copy link
Contributor

@Sigmabrogz Sigmabrogz commented Mar 18, 2026

Fixes #1453

Zod enums (both in z.enum and Zod 4's z.enum) are inherently string literals. Previously, ZodToJsonSchemaConverter only specified the enum array without indicating the type: 'string', causing downstream OpenAPI rendering tools (like Stoplight) to fallback to treating it as any. This PR explicitly adds type: 'string'.

Summary by CodeRabbit

  • Bug Fixes
    • Enum schemas now include explicit string type annotation in JSON Schema output for improved clarity and spec compliance.

@dosubot dosubot bot added the size:S This PR changes 10-29 lines, ignoring generated files. label Mar 18, 2026
@coderabbitai
Copy link

coderabbitai bot commented Mar 18, 2026

📝 Walkthrough

Walkthrough

The PR adds an explicit type: 'string' field to Zod enum JSON Schema conversions across both standard and Zod v4 converter implementations. Previously, enums output only { enum: [...] }, now they include { type: 'string', enum: [...] }. Test expectations are updated accordingly.

Changes

Cohort / File(s) Summary
Converter Implementation
packages/zod/src/converter.ts, packages/zod/src/zod4/converter.ts
Updated enum schema generation to include explicit type: 'string' field alongside enum values, tightening type assertions in JSON Schema output.
Test Expectations
packages/zod/src/converter.test.ts, packages/zod/src/zod4/converter.native.test.ts, packages/zod/src/zod4/converter.structure.test.ts
Updated test inputs/expectations to reflect new schema structure with type: 'string' in enum and tuple-wrapped enum test cases.

Estimated code review effort

🎯 1 (Trivial) | ⏱️ ~5 minutes

Possibly related PRs

Suggested labels

size:M

Poem

🐰 A string enum hops into view,
With type now explicit, clearer and true,
No more ambiguous "any" in sight,
OpenAPI specs now shine so bright! ✨

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and concisely describes the main change: adding explicit string type generation for Zod enums in the JSON Schema output.
Linked Issues check ✅ Passed The changes directly address issue #1453 by adding type: 'string' to Zod enum schemas in both the main converter and Zod4 converter, eliminating the need for downstream workarounds.
Out of Scope Changes check ✅ Passed All changes are directly scoped to fixing Zod enum schema generation by adding the type: 'string' field; no unrelated modifications are present.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
📝 Coding Plan
  • Generate coding plan for human review comments

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request resolves an issue where Zod enum types were not accurately represented in their generated JSON schemas. By explicitly adding the type: 'string' property to enum schemas, the change ensures that these types are correctly recognized as string literals by OpenAPI tools and other schema consumers, thereby improving schema fidelity and interoperability.

Highlights

  • JSON Schema Generation for Zod Enums: Previously, Zod enums (both z.enum and Zod 4's z.enum) were converted to JSON schemas without explicitly specifying type: 'string', which is crucial for correct interpretation by downstream tools.
  • OpenAPI Compatibility Fix: The absence of type: 'string' caused OpenAPI rendering tools, such as Stoplight, to incorrectly default to any for enum types. This fix ensures proper type inference.
  • Explicit Type Declaration: The ZodToJsonSchemaConverter has been updated to explicitly add type: 'string' to the generated JSON schema for all Zod enum types, aligning with standard JSON Schema practices for string literals.
  • Test Case Updates: Corresponding test cases across converter.test.ts, converter.native.test.ts, and converter.structure.test.ts were updated to reflect the new, correct schema output including type: 'string' for enums.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for GitHub and other Google products, sign up here.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

@dosubot dosubot bot added the bug Something isn't working label Mar 18, 2026
Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request aims to fix an issue where Zod enums were missing the type: 'string' in the generated JSON schema. The changes for Zod v3 are correct. However, the implementation for Zod v4 introduces a critical issue by incorrectly assuming all enums are string-based, which will lead to incorrect schemas for numeric enums. I've provided a specific comment and a code suggestion to address this.

case 'enum': {
const enum_ = schema as $ZodEnum
return [true, { enum: Object.values(enum_._zod.def.entries) }]
return [true, { type: 'string', enum: Object.values(enum_._zod.def.entries) }]
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

critical

This change incorrectly assumes that all Zod enums are string-based. In Zod v4, z.enum() can also be used with numeric native enums. Hardcoding type: 'string' will produce an incorrect schema for numeric enums.

The type should be determined dynamically based on the enum values. It would also be beneficial to add a test case for a numeric enum to prevent future regressions.

            return (() => {
              const values = Object.values(enum_._zod.def.entries);
              if (values.every((v) => typeof v === 'string')) {
                return [true, { type: 'string', enum: values }];
              }
              if (values.every((v) => typeof v === 'number')) {
                return [true, { type: 'number', enum: values }];
              }
              return [true, { enum: values }];
            })()

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (1)
packages/zod/src/converter.ts (1)

343-353: Consider whether ZodNativeEnum should also include type for string-only enums.

The ZodEnum case now correctly emits type: 'string', but ZodNativeEnum at lines 349-352 still emits only { enum: [...] } without a type. This is technically correct since TypeScript native enums can contain mixed types (strings and numbers), but for string-only native enums like the test case ExampleEnum, the schema won't include type: 'string'.

If intentional, this asymmetry between z.enum() and z.nativeEnum() with string values may still cause downstream OpenAPI renderers to treat string-only native enums as any. Consider documenting this limitation or adding type inference based on enum value types in a follow-up.

💡 Optional: Infer type for string-only native enums
 case ZodFirstPartyTypeKind.ZodNativeEnum: {
   const schema_ = schema as ZodNativeEnum<EnumLike>
+  const values = Object.values(schema_._def.values)
+  const allStrings = values.every(v => typeof v === 'string')

-  return [true, { enum: Object.values(schema_._def.values) }]
+  return [true, allStrings ? { type: 'string', enum: values } : { enum: values }]
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/zod/src/converter.ts` around lines 343 - 353, The ZodNativeEnum
branch in converter.ts returns only { enum: [...] } which omits a 'type' for
string-only native enums; update the ZodNativeEnum handling in the converter
(the switch case for ZodFirstPartyTypeKind.ZodNativeEnum / the schema_ variable
of type ZodNativeEnum) to inspect Object.values(schema_._def.values) and, if
every value is a string, return [true, { type: 'string', enum: values }],
otherwise keep the existing behavior (return [true, { enum: values }]) so
mixed-type enums remain unchanged.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@packages/zod/src/converter.ts`:
- Around line 343-353: The ZodNativeEnum branch in converter.ts returns only {
enum: [...] } which omits a 'type' for string-only native enums; update the
ZodNativeEnum handling in the converter (the switch case for
ZodFirstPartyTypeKind.ZodNativeEnum / the schema_ variable of type
ZodNativeEnum) to inspect Object.values(schema_._def.values) and, if every value
is a string, return [true, { type: 'string', enum: values }], otherwise keep the
existing behavior (return [true, { enum: values }]) so mixed-type enums remain
unchanged.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 911832ff-20c2-4c02-808f-9327fef9d8cc

📥 Commits

Reviewing files that changed from the base of the PR and between a45fc95 and 463987b.

📒 Files selected for processing (5)
  • packages/zod/src/converter.test.ts
  • packages/zod/src/converter.ts
  • packages/zod/src/zod4/converter.native.test.ts
  • packages/zod/src/zod4/converter.structure.test.ts
  • packages/zod/src/zod4/converter.ts

@Sigmabrogz
Copy link
Contributor Author

Closing this as a duplicate of #1478 which has been approved.

@Sigmabrogz Sigmabrogz closed this Mar 18, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working size:S This PR changes 10-29 lines, ignoring generated files.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Zod string literal enums are generated in OpenAPI spec without a string type

1 participant